package lingnan.controller;

import lingnan.entity.User;
import lingnan.service.BookService;
import lingnan.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.*;

/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2020-06-12 17:08:14
 */
@RestController
@RequestMapping("user")
public class UserController {
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;
    @Resource
    private BookService bookService;

    /**
     * 登录
     *
     * @param name 用户名/账号
     * @param password 密码
     * @return 用户对象
     */
    @PostMapping("login")
    public Object login(String name, String password, HttpSession session) {
        //进行登录
        System.out.println("Login......");
        User bean = userService.login(name, password);
        if (bean == null) {
            //登录失败
            return null;
        }
        //登录成功
        //session保存
//        session.setAttribute("loginUser", bean);
        //打印
        System.out.println("loginName:::" + bean.getName() + ", loginPassword:::" + bean.getPassword());
        System.out.println(":::登录成功！:::");
        System.out.println("上一次登录时间:::" + bean.getLastLoginDate());
        bean.setName(name);
        bean.setLastLoginDate(new Date());
        userService.update(bean);
        System.out.println("本次登录时间:::" + bean.getLastLoginDate());
        System.out.println("user:::" + bean);
        //成功，返回bean
        return bean;
    }

    @RequestMapping("loginOut")
    public void loginOut(HttpSession session){
        System.out.println("服务端：退出登录！");
        session.removeAttribute("loginUser");
    }

    /**
     * 注册
     *
     * @param bean 用户对象
     * @param cfmPassword 确认密码
     * @return 是否成功
     */
    @PostMapping("reg")
    public Object reg(@RequestBody User bean, @RequestParam("cfmPassword") String cfmPassword) {
        System.out.println("reg:::" + bean);
        System.out.println("再次确认的密码:::" + cfmPassword);
        //结果
        String result;
        //判断两次密码是否一致
        if(!bean.getPassword().equals(cfmPassword)) {
            result = "msgCfmPasswordError";
            System.out.println("result:::" + result);
            return result;
        }

        //判断用户名重复
        if (userService.queryByName(bean.getName()) != null) {
            result = "msgNameUsedError";
            System.out.println("result:::" + result);
            return result;
        }

        //给注册时间赋值
        bean.setRegDate(new Date());
        System.out.println("注册时间:::"+bean.getRegDate());

        //注册
        boolean flag = userService.insert(bean);
        if (flag) {
            System.out.println("注册成功!");
            result = "msgRegSuccess";
            return result;
        }
        System.out.println("注册失败!");
        result = "msgRegFailed";
        return result;
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("getById/{id}")
    @ResponseBody
    public User getById(@PathVariable("id")  Integer id) {
        System.out.println("id:::"+id);
        return userService.queryById(id);
    }

    /**
     * 查询所有对象
     *
     * @return 所有对象
     */
    @GetMapping("queryAll")
    @ResponseBody
    public Object queryAll() {
        return userService.queryAll();
    }

    /**
     * 添加和修改用户
     *
     * @param bean 用户对象
     * @return 是否成功
     */
    @PostMapping("save")
    @ResponseBody
    public Object save(User bean) {
        boolean result = false;
        //判断账号是否存在

        //判断是添加还是编辑
        if (bean.getId() != null) {
            //编辑
            result = userService.update(bean);
        } else {
            //添加
            bean.setRegDate(new Date());
            result = userService.insert(bean);
        }

        return result;
    }

    /**
     * 新增数据
     *
     * @param bean 实例对象
     * @return 是否成功
     */
    @PostMapping("insert")
    @ResponseBody
    public Object insert(User bean) {
        return userService.insert(bean);
    }

    /**
     * 修改数据
     *
     * @param bean 实例对象
     * @return 是否成功
     */
    @PostMapping("update")
    @ResponseBody
    public String update(@RequestBody User bean,
                         @RequestParam(value = "cfmPassword", required = false) String cfmPassword,
                         @RequestParam(value = "oldPassword", required = false) String oldPassword,
                         @RequestParam(value = "checkPhone", required = false) String checkPhone,
                         HttpSession session){

        //服务端处理
        System.out.println("服务端处理:");

        //打印
        //获取当前用户的信息（更新前的信息，主要用来验证）
        Integer uid = bean.getId();
        User user = userService.queryById(uid);
        System.out.println("当前用户的原本信息:::" + user);
        System.out.println("当前用户的id为:::" + uid);
        System.out.println("当前用户的更新信息:::" + bean);

        //先判断用户名是否改变，如果改变了要判断用户名是否已经被使用
        if((bean.getName() != null) && bean.getName().equals(user.getName())) {
            System.out.println("更新提示:::用户名不变");
        } else if(userService.queryByName(bean.getName()) != null) {
//            model.addAttribute("msgNameUsed", "该用户名已经被使用!");
            return "msgNameUsedError";
        }

        //如果是密码更新
        if(oldPassword != null) {
            //打印
            System.out.println("密码更新（服务端）:");
            System.out.println("oldPassword:::" + oldPassword);
            System.out.println("cfmPassword:::" + cfmPassword);
            //先进行原密码验证
            if(!oldPassword.equals(user.getPassword())){
//                model.addAttribute("msg", "原密码错误！请重试!");
                return "msgOldPassError";
            }
            //再判断两次密码是否一致
            if(cfmPassword != null){
                if(!bean.getPassword().equals(cfmPassword)) {
//                    model.addAttribute("msg", "两次输入密码不一致!");
                    return "msgTwoPassError";
                }
            }
        //如果是找回密码
        }else if (checkPhone != null) {
            System.out.println("找回密码（服务端）:");
            System.out.println("checkPhone:::" + checkPhone);
            //先进行手机验证
            if(!checkPhone.equals(user.getPhone())){
//                model.addAttribute("msg", "手机验证错误！请重试!");
                return "msgPhoneError";
            }
            //再判断两次密码是否一致
            if(cfmPassword != null){
                if(!bean.getPassword().equals(cfmPassword)) {
//                    model.addAttribute("msg", "两次输入密码不一致!");
                    return "msgTwoPassError";
                }
            }
        }

        //执行更新
        boolean isUpdate = userService.update(bean);
        if (isUpdate){
            //更新用户信息成功
            User newBean = userService.queryById(uid);
            System.out.println("更新后的用户信息:::" + newBean);
            //当前登录的账户信息改变
            session.setAttribute("loginUser", newBean);
//            model.addAttribute("msg", "用户信息已更新！");
//            return "msgUpdateSuccess";
        }else {
            //更新用户信息失败
//            model.addAttribute("msg", "更新失败!请重试！");
            return "msgUpdateFailed";
        }

        return "success";
    }

    /**
     * 通过主键删除数据
     *
     * @param ids 主键
     * @return 影响行数
     */
    @DeleteMapping("deleteByIds/{ids}")
    @ResponseBody
    public Object deleteByIds(@PathVariable("ids") List<Integer> ids){
        return userService.deleteByIds(ids);
    }


    /**
     * 以json数据格式返回所有用户数据
     * @return
     */
    @GetMapping("/getListJson")
    @ResponseBody
    public List<User> getListJson() {
        System.out.println("getListJson");
        return userService.queryAll();
    }
    //上面为user.jsp实验用的方法，下面两个才是查询json方法  getMapjson为显示全部数据 ，findjson是条件查询输出数据
    @GetMapping(value="/getMapJson")
    @ResponseBody
    public Map<String, Object> getMapJson(){
        List<User> users = userService.queryAll();
        int count = userService.countAllUser();
        System.out.println("coun:::"+count);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("msg","");
        map.put("code",0);
        map.put("count",count);
        map.put("data",users);
        System.out.println(map);
        return map;
    }

    @PostMapping(value="/findJson")
    @ResponseBody
    public Map<String, Object> findJson(@RequestParam("value") String value,@RequestParam("domain") String domain){
        User bean=new User();
        System.out.println("value:::"+value);
        System.out.println("domain:::"+domain);
        System.out.println("类型是：：："+domain.getClass().getName());
        if(domain.equals("0"))
            bean.setId(Integer.parseInt(value));
        if(domain.equals("1"))
            bean.setName(value);
        if(domain.equals("2"))
            bean.setPassword(value);
        if(domain.equals("3"))
            bean.setSex(value);
        if(domain.equals("4"))
            bean.setPhone(value);
        if(domain.equals("5"))
            bean.setEmail(value);
        if(domain.equals("6"))
            bean.setAccess(Integer.parseInt(value));

        List<User> users = userService.findByAll(bean);
        int count = userService.countAllUser();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("msg","");
        map.put("code",0);
        map.put("count",count);
        map.put("data",users);
        System.out.println(map);
        return map;
    }
    @PostMapping(value="/deleteJson")
    @ResponseBody
    public String deleteJson(@RequestParam("id") Integer id){
        //删除要用查找 找到这个值返回整条数据 外面会输出1表示有数据 然后在外面删除
        List<Integer> ids=new ArrayList<Integer>();
        ids.add(id);
        int flag=0;
        flag = userService.deleteByIds(ids);
        if(flag!=0)
            return "1";
        return "0";
    }

    //下面两个为json更新 updateGo为页面跳转显示更新页面，update是执行更新操作
    @RequestMapping(value="/updateGo")
    public String updateGo(@RequestParam("id")int id,@RequestParam("name") String name,@RequestParam("password") String password
            ,@RequestParam("sex") String sex,@RequestParam("phone") String phone
            ,@RequestParam("email") String email,@RequestParam("access") int access){

        return "manageuserupdate";
    }

    @PostMapping(value="/updatejson")
    @ResponseBody
    public boolean updatejson(@RequestBody User bean){

        return userService.update(bean);
    }
//    @RequestMapping(value="/mine")
//    public String mine(HttpSession session){
//        User user=(User) session.getAttribute("loginUser");
//        int id=user.getId();
//        System.out.println("id:::"+id);
//        session.setAttribute("allBook", bookService.getBookAllByUser(id));
//        session.setAttribute("checking", bookService.getBookAllByStateUser(1,id));
//        session.setAttribute("outDate", bookService.getBookAllByStateUser(0,id));
//        session.setAttribute("confirm", bookService.getBookAllByStateUser(2,id));
//        System.out.println("allBook:::"+bookService.getBookAllByUser(id));
//        System.out.println("checking:::"+bookService.getBookAllByStateUser(1,id));
//        System.out.println("outDate:::"+bookService.getBookAllByStateUser(0,id));
//        System.out.println("confirm:::"+bookService.getBookAllByStateUser(2,id));
//        return "user";
//    }


}